package com.dzsw.javabase.str;

import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.List;

public class GetUnicodeSample {

    public static void main(String[] args) {
        String str = "＂This is a test. 中文";
        char c = '＂';
        System.out.println(getUnicode3(c));
        getUnicode(str);
    }

    public static void getUnicode(String str) {
        char[] chars = str.toCharArray();
        for (char c : chars) {
            System.out.println(c + " --- " + getUnicode3(c));
        }
    }

    public static String getUnicode3(char aChar) {
        String x = Integer.toHexString(aChar);
        if (x.length() <= 2) {
            x = "\\u00" + x;
        } else {
            x = "\\u" + x;
        }
        return x;
    }

    /**
     * 原文链接：https://blog.csdn.net/lovepeacee/article/details/99678086
     * @throws Exception
     */
    public static void getUnicode() throws Exception {
        // 获取unicode码的几种方式
        // 第一种
        System.err.println("第一种-----toCodePoints");
        String test = "a汉字";
        int[] asds = StringUtils.toCodePoints(test);
        for (int asd : asds) {
            System.err.println("int整型:" + asd);
            String x = Integer.toHexString(asd);
            if (x.length() <= 2) {
                x = "\\u00" + x;
            } else {
                x = "\\u" + x;
            }
            System.err.println("unicode码" + x);
        }
        //第二种
        System.err.println("第二种-----getBytes");
        byte[] bytes = test.getBytes("unicode");

        List<Object> list = new ArrayList<>();
        for (byte aByte : bytes) {
            System.err.println("byte字节:" + aByte);
            String x = Integer.toHexString(aByte);
            if ((-2 != aByte) && (-1 != aByte)) {
                list.add(x);
            }
        }
        for (int i = 0; i < list.size(); i = i + 2) {
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.append(list.get(i));
            stringBuilder.append(list.get(i + 1));
            if (stringBuilder.length() < 4) {
                for (int j = 0; j < 4 - stringBuilder.length(); j++) {
                    stringBuilder.insert(0, "0");
                }
            }
            System.err.println("unicode码" + "\\u".concat(stringBuilder.toString()));
        }
        // 第三种
        System.err.println("第三种-----toCharArray");
        char[] chars = test.toCharArray();
        for (char aChar : chars) {
            System.err.println("char字符:" + aChar);
            String x = Integer.toHexString(aChar);
            if (x.length() <= 2) {
                x = "\\u00" + x;
            } else {
                x = "\\u" + x;
            }
            System.err.println("unicode码" + x);
        }
    }
}
